//
//  RefreshVM.m
//  Design
//
//  Created by boitx on 02/10/2017.
//  Copyright © 2017 boitx. All rights reserved.
//

#import "RefreshVM.h"

static NSInteger pageIndex = 1;
static NSInteger pageCount = 20;

@implementation RefreshVM

- (void)configRefresh{
    MJRefreshHeader *header = [MJRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestHeaderData)];
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestFooterData)];
    
    [footer setTitle:@"没有更多啦~" forState:MJRefreshStateNoMoreData];
    [footer setTitle:@"" forState:MJRefreshStateIdle];
    
    self.refreshView.mj_header = header;
    self.refreshView.mj_footer = footer;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    [self.refreshView.mj_header beginRefreshing];
}

- (void)requestHeaderData{
    pageIndex = 1;
    [self.dataArray removeAllObjects];
    if (self.isPost) {
        [Utils showHudWithTitle:@"加载中" target:nil];
        [NetWork postDataWithString:self.urlStr body:self.params successBlock:^(id responseObj) {
            NSLog(@"json:%@", responseObj);
            [Utils closeHud];
            [self.refreshView.mj_header endRefreshing];
            NSArray *typeArr = [responseObj allKeys];
            if ([typeArr containsObject:@"status_code"]) {
                [Utils showHudWithTitle:responseObj[@"message"] target:nil];
            }else{
                [self parseDict:responseObj];
            }
            
        } failBlock:^(NSError *error) {
            [Utils closeHud];
        }];
    }else{
        [Utils showHudWithTitle:@"加载中" target:nil];
        [NetWork getDataWithString:self.urlStr parma:[self configParams] SuccessBlock:^(id responseObj) {
            NSLog(@"json:%@", responseObj);
            [Utils closeHud];
            [self.refreshView.mj_header endRefreshing];
            NSArray *typeArr = @[];
            if ([responseObj isKindOfClass:[NSDictionary class]]) {
                typeArr = [responseObj allKeys];
            }
            if ([typeArr containsObject:@"status_code"]) {
                [Utils showHudWithTitle:responseObj[@"message"] target:nil];
            }else{
                [self parseDict:responseObj];
            }
            
        } FailBlock:^(NSError *error) {
            [Utils closeHud];

        }];
    }
    
}
- (void)requestFooterData{
    pageIndex++;
    if (self.isPost) {
        [NetWork postDataWithString:self.urlStr body:[self configParams] successBlock:^(id responseObj) {
            [self.refreshView.mj_footer endRefreshing];
            NSString *type = responseObj[@"status_code"];
            if ([type isEqualToString: @"000000"]) {
                self.refreshView.contentOffset = CGPointZero;
                [self parseDict:responseObj];
            }else{
                if ([responseObj isKindOfClass:[NSString class]]) {
                    [Utils showHudWithTitle:responseObj target:nil];
                }
            }
            
        } failBlock:^(NSError *error) {
            [Utils closeHud];
        }];
        
    }else{
        [NetWork getDataWithString:self.urlStr parma:self.params SuccessBlock:^(id responseObj) {
            [self.refreshView.mj_footer endRefreshing];
            NSString *type = responseObj[@"status_code"];
            if ([type isEqualToString: @"000000"]) {
                self.refreshView.contentOffset = CGPointZero;
                [self parseDict:responseObj];
            }else{
                if ([responseObj isKindOfClass:[NSString class]]) {
                    [Utils showHudWithTitle:responseObj target:nil];
                }
            }
        } FailBlock:^(NSError *error) {
            [Utils closeHud];
        }];
    }
    
}

#pragma mark - 正常请求
- (void)requestDataNormal{
    [Utils showHudWithTitle:@"加载中" target:nil];
    [NetWork postDataWithString:self.urlStr body:self.params successBlock:^(id responseObj) {
        NSLog(@"json:%@", responseObj);
        [Utils closeHud];
        NSArray *typeArr = [responseObj allKeys];
        if ([typeArr containsObject:@"status_code"]) {
            [Utils showHudWithTitle:responseObj[@"message"] target:nil];
        }else{
            [self getNormalModel:responseObj];
        }
        
    } failBlock:^(NSError *error) {
        [Utils closeHud];

    }];
    
}
- (void)getRequestDataNormal{
    [Utils showHudWithTitle:@"加载中" target:nil];
    [NetWork getDataWithString:self.urlStr parma:self.params SuccessBlock:^(id responseObj) {
        NSLog(@"json:%@", responseObj);
        [Utils closeHud];
        NSArray *typeArr = [responseObj allKeys];
        if ([typeArr containsObject:@"status_code"]) {
            [Utils showHudWithTitle:responseObj[@"message"] target:nil];
        }else{
            [self getNormalModel:responseObj];
        }
        
        
    } FailBlock:^(NSError *error) {
        [Utils closeHud];
        NSLog(@"Error:%@",error);
    }];
    
}



-(void)getNormalModel:(id)obj{
    //不转model 直接返回数据
    if (!self.dataClass) {
        if (self.requestResultBlock) {
            self.requestResultBlock(obj);
        }
        return;
    }
    
    if ([obj isKindOfClass:[NSArray class]]) {
        NSArray *arr = [self.dataClass mj_objectArrayWithKeyValuesArray:obj];
        if (self.requestResultBlock) {
            self.requestResultBlock(arr);
        }
        return;
    }
    if ([obj isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dataDic = obj;
        if (dataDic.allKeys.count == 1) {
            id data = dataDic[dataDic.allKeys.firstObject];
            if ([data isKindOfClass:[NSArray class]]) {
                NSArray *arr = [self.dataClass mj_objectArrayWithKeyValuesArray:data];
                if (self.requestResultBlock) {
                    self.requestResultBlock(arr);
                }
            }else if ([data isKindOfClass:[NSDictionary class]]){
                NSObject *model = [self.dataClass mj_objectWithKeyValues:data];
                if (self.requestResultBlock) {
                    self.requestResultBlock(model);
                }
            }
        }else{
            NSObject *model = [self.dataClass mj_objectWithKeyValues:obj];
            if (self.requestResultBlock) {
                self.requestResultBlock(model);
            }
        }
        
    }

}


- (NSDictionary *)configParams
{
    NSMutableDictionary *muParams = self.params.mutableCopy;
    [muParams setObject:@(pageIndex) forKey:@"page"];
//    [muParams setObject:@(pageCount) forKey:@"pageCount"];
    
    return muParams;
}

- (void)parseDict:(id)dict{
    //不转model 直接返回数据
    if (!self.dataClass) {
        if (self.requestResultBlock) {
            self.requestResultBlock(dict);
        }
        return;
    }
    NSArray *tempArr = [NSArray new];

    if ([dict isKindOfClass:[NSArray class]]) {
        tempArr = [self.dataClass mj_objectArrayWithKeyValuesArray:dict];
    }else{
        NSString *keyStr = nil;
        for (NSString *key in [dict allKeys]) {
            if ([key isEqualToString:@"data"]) {
                keyStr = key;
                break;
            }
        }
        tempArr = [self.dataClass mj_objectArrayWithKeyValuesArray:dict[keyStr]];
        
    }
    
    if (tempArr.count > 0) {
        [self.dataArray addObjectsFromArray:tempArr];
        if ([dict isKindOfClass:[NSDictionary class]]) {
            [self judgeRefreshState:dict];
            
        }
//        if (tempArr.count < 20 && self.dataArray.count > 0) {
//            self.refreshView.mj_footer.state = MJRefreshStateNoMoreData;
//        }else{
//            self.refreshView.mj_footer.state = MJRefreshStateIdle;
//        }
    }else{
        self.refreshView.mj_footer.state = MJRefreshStateIdle;
    }
    if (pageIndex == 1) {
        self.refreshView.contentOffset = CGPointZero;
    }
    if ([self.refreshView respondsToSelector:@selector(reloadData)]) {
        [self.refreshView performSelector:@selector(reloadData)];
    }
}

-(void)judgeRefreshState:(NSDictionary *)dataDic{
    if ([dataDic.allKeys containsObject:@"meta"]) {
        NSDictionary *links = dataDic[@"meta"][@"links"];
        if ([[Utils id2str:links[@"previous"]] isEqualToString:@""]) {
            self.refreshView.mj_footer.state = MJRefreshStateNoMoreData;

        }else{
            self.refreshView.mj_footer.state = MJRefreshStateIdle;

        }
    }
}


@end
